package com.example.clientmessage;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;

import com.example.utils.PostUtil;
import com.google.android.gcm.GCMRegistrar;

public class MainActivity extends Activity {

	private static final String SENDER_ID = "715020791943";
	private static final String TAG = null;
	private String regId= "123";
	

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// GCMRegistrar.checkDevice(this);
		GCMRegistrar.checkManifest(this);

//		boolean isRegisteredOnServer = GCMRegistrar.isRegisteredOnServer(this);
//		
//		if (!isRegisteredOnServer)
//		{
//			GCMRegistrar.unregister(this);	
//		}
		
		regId = GCMRegistrar.getRegistrationId(this);
		
		if (regId.equals("")) {
			GCMRegistrar.register(this, SENDER_ID);
		} else {
			Log.v(TAG, "Already registered");
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}

	public void sendMessage(View view) {
		JSONObject jsonObject = new JSONObject();
		EditText editText = (EditText) findViewById(R.id.sendText);
		String message = editText.getText().toString();
		regId = GCMRegistrar.getRegistrationId(this);
		try {
			jsonObject.put("senderRegId", regId);
			jsonObject.put("receiverRegId", regId);
			jsonObject.put("data", message);
			// Send message
			PostUtil.post(
					"http://" + PostUtil.APP_SERVER + ":8080/JAXB/rest/messages/send",
					jsonObject);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void sendMessage2(View view) {
		JSONObject jsonObject = new JSONObject();
		EditText editText = (EditText) findViewById(R.id.sendText);
		String message = editText.getText().toString();
		regId = GCMRegistrar.getRegistrationId(this);
		try {
			jsonObject.put("senderNumber", "test");
			jsonObject.put("receiverNumber", "test");
			jsonObject.put("data", message);
			// Send message
			PostUtil.post(
					"http://" + PostUtil.APP_SERVER + ":8080/JAXB/rest/messages/send2",
					jsonObject);
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
